import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-11-17
 * Time: 20:05
 */
public class Solution {
    public int findMaxLength(int[] nums) {
        int maxLength = 0;
        Map<Integer,Integer> map = new HashMap<>();
        int count = 0;
        int n = nums.length;
        map.put(count,-1);

        //遍历数组
        for (int i = 0; i < n; i++) {
            int num = nums[i];
            if (num == 1) {
                count++;
            }else {
                count--;
            }

            if (map.containsKey(count)) {
                int prevIndex = map.get(count);
                maxLength = Math.max(maxLength,i-prevIndex);
            }else {
                map.put(count,i);
            }
        }

        return maxLength;
    }
}
